package com.application.job;

import com.application.common.OrderStatus;
import com.application.model.Order;
import com.application.model.OrderFlow;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class OrderStatusJob implements Job{

    private ScheduledExecutorService service;
    public void start(int ordersId){

        service = Executors.newScheduledThreadPool(10);
        //60min后执行一次
        service.schedule(new OrdersStatusExecutor(getClass().getSimpleName(), ordersId), 3610, TimeUnit.SECONDS);

//        long initialDelay = 1;
//        long period = 1;
        // 从现在开始1秒钟之后，每隔1秒钟执行一次job1
//        service.scheduleAtFixedRate(new OrdersStatusExecutor("job1"), initialDelay, period, TimeUnit.SECONDS);
        // 从现在开始2秒钟之后，每隔2秒钟执行一次job2; 每次执行时间为上一次任务结束起向后推一个时间间隔
//        service.scheduleWithFixedDelay(new OrdersStatusExecutor("job2"), initialDelay, period, TimeUnit.SECONDS);
    }

    public void firstScan(){
        new OrdersStatusExecutor("job0", null).run();
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        new OrdersStatusExecutor("job1", null).run();
    }

    class OrdersStatusExecutor implements Runnable {

        private String jobName;
        private Integer ordersId;

        OrdersStatusExecutor(String jobName, Integer ordersId) {
            this.jobName = jobName;
            this.ordersId = ordersId;
        }

        @Override
        public void run() {
//            Orders orders = Orders.dao.findById(ordersId);
            String sql = "SELECT * from t_order where order_status = "+ OrderStatus.PAY_WAIT +
                    " and create_time < DATE_ADD(?,INTERVAL -60 minute)";
            if(ordersId != null){
                sql += " and id = " + ordersId;
            }
            List<Order> orderList = Order.dao.find(sql, new Date());
            for (Order order : orderList) {
                order.setOrder_status(OrderStatus.CLOSED_TIMEOUT);
                order.update();//修改订单状态为已过期

                //同步变更订单流程
                OrderFlow.dao.create(order.getId(), OrderStatus.CLOSED_TIMEOUT, 0, "订单超时");
            }

            System.out.println(jobName + " is over");

            if(service != null){
                service.shutdown();
            }
        }
    }


    public static void main(String[] args) {
        System.out.println("start:" + System.currentTimeMillis());
        new OrderStatusJob().start(50);
        System.out.println("end:" + System.currentTimeMillis());
    }

}